package cn.oms.auth.provider.service.impl;

import cn.oms.auth.provider.dao.entity.Permission;
import cn.oms.auth.provider.dao.entity.Role;
import cn.oms.auth.provider.dao.entity.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private RestTemplate restTemplate;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String url="http://auth-service/auth/auth/api?username={1}";
        User user=restTemplate.getForObject(url, User.class,username);
        if(user==null){
            throw new  UsernameNotFoundException("用户名不存在");
        }
        url="http://auth-service/v1/auth/permissions?id={1}";
        //当控制器方法返回List类型时
        // 我们使用List指定泛型的类型数组来接收

        // 查询用户权限
        Permission[]  permissions=restTemplate.getForObject(url , Permission[].class , user.getUserId());
        url="http://auth-service/v1/auth/roles?id={1}";

        // 查询用户角色
        Role[] roles=restTemplate.getForObject(url , Role[].class , user.getUserId());
        //定义auth数组,包含所有角色和权限的名称
        String[] auth=new String[permissions.length+roles.length];
        int i=0;
        for(Permission p: permissions){
            auth[i++]=p.getPermissionName();
        }
        for(Role r: roles){
            auth[i++]=r.getRoleName();
        }
        //构建UserDetails对象
        UserDetails u= org.springframework.security.core.userdetails
                .User.builder()
                .username(user.getUserName())
                .password(user.getUserPassword())
                .authorities(auth)
                .accountLocked(user.getLocked()==1)
                .disabled(user.getEnabled()==0)
                .build();
        // 千万不要忘记返回u
        return u;
    }
}

